// OptionsDlg.h : interface of the COptionsDlg class
//
/////////////////////////////////////////////////////////////////////////////

#pragma once

#include "MagicScannerClient.h"
#include "resource.h"

class COptionsDlg : public ATL::CDialogImpl<COptionsDlg>
{
	bool            m_bPasswordChanged;

public:
	enum { IDD = IDD_OPTIONS };

	COptionsDlg()
		: m_bPasswordChanged(false)
	{
	}

	BEGIN_MSG_MAP(COptionsDlg)
		MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
		COMMAND_HANDLER(IDC_EDIT_PASSWORD, EN_CHANGE, OnPasswordChange)
		COMMAND_ID_HANDLER(IDOK, OnOK)
		COMMAND_ID_HANDLER(IDCANCEL, OnCancel)
		COMMAND_ID_HANDLER(IDC_REGISTER, OnRegister)
	END_MSG_MAP()

	LRESULT OnRegister(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		DWORD_PTR dwRet = (DWORD_PTR)::ShellExecute(0, _T("open"),
			_T("http://www.wi2geo.ru/user/reg/"), 0, 0, SW_SHOWNORMAL);
		return dwRet > 32;
	}

	LRESULT OnPasswordChange(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		m_bPasswordChanged = true;
		return 0;
	}

	virtual void Init
		( IN LPARAM lParam
		) = 0;

	virtual bool IsStatusEnabled() = 0;
	virtual void SetStatusEnabled
		( IN bool bEnabled
		) = 0;
	virtual _tstring GetUserName() = 0;
	virtual void SetUserName
		( IN const _tstring& strUserName
		) = 0;
	virtual bool IsPasswordEmpty() = 0;
	virtual void SetPasswordHash
		( IN const std::string& strPasswordHash
		) = 0;

	LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
	{
		Init(lParam);

		CheckDlgButton(IDC_ENABLE_GEO_STATUS, IsStatusEnabled());
		SetDlgItemText(IDC_EDIT_NAME, GetUserName().c_str());

		if (!IsPasswordEmpty())
			SetDlgItemText(IDC_EDIT_PASSWORD, _T("******"));

		CenterWindow();
		m_bPasswordChanged = false;
		return TRUE;
	}

	LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		TCHAR szBuffer[256];

		SetStatusEnabled(!!IsDlgButtonChecked(IDC_ENABLE_GEO_STATUS));

		if (!GetDlgItemText(IDC_EDIT_NAME, szBuffer, ARRAYSIZE(szBuffer)))
			szBuffer[0] = '\x0';

		SetUserName(szBuffer);

		if (m_bPasswordChanged)
		{
			if (!GetDlgItemText(IDC_EDIT_PASSWORD, szBuffer, ARRAYSIZE(szBuffer)))
				szBuffer[0] = '\x0';

			std::string strHash = MD5Hash((LPCSTR)ATL::CT2AEX<256>(szBuffer, CP_UTF8));
			SetPasswordHash(strHash.c_str());
		}

		EndDialog(wID);
		return 0;
	}

	LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		EndDialog(wID);
		return 0;
	}
};
